# 4 - 4 梯度
import numpy as np

def numerical_graient(f, x):
    h = 1e-4  # 0.0001
    grad = np.zeros_like(x)

    for idx in range(x.size):
        tmp_val = x[idx]    # f(x + h)的计算
        x[idx] = tmp_val + h
        fxh1 = f(x)

        # f(x - h)的计算
        x[idx] = tmp_val - h
        fxh2 = f(x)

        grad[idx] = (fxh1 - fxh2) / (2*h)
        x[idx] = tmp_val  # 还原值

    return grad

def f2(x):
    return x[0]**2 + x[1]**2

if __name__ == '__main__':
    x = np.array([3.0, 4.0])
    grad = numerical_graient(f2, x)
    print(grad)